package com.baidu.influx.demo;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;

import java.time.Instant;

/**
 * @author: tony
 * @date: 2022/9/23 3:23
 * @description: 这里是使用同步方式向InfluxDB写入数据的示例代码
 *
 */
public class Write1 {

    /** token 操作时需要换成自己的 **/
    private static char[] token = "zAzRrZGXUyyrqlCx9BEupsTY1-v701MDkOze8M-sRiZaAvde5jStvO62_PFgPQF69PSkq1s7U05H4MWuYnQ9KA==".toCharArray();

    /** 组织名称 **/
    private static String org = "root";

    /** InfluxDB服务提供的url **/
    private static String url = "http://localhost:8086/";

    /** 存储桶名称 **/
    private static String bucket = "example01";

    public static void main(String[] args) {

        InfluxDBClient influxDBClient = InfluxDBClientFactory.create(url, token, org, bucket);
        WriteApiBlocking writeApiBlocking = influxDBClient.getWriteApiBlocking();

        // 0. 使用InflxuDB行协议写入
//        writeApiBlocking.writeRecord(WritePrecision.MS,"temperature,location=north value=50");

        // 1. 使用Point写入
//        Point point = Point.measurement("temperature")
//                .addTag("location", "west")
//                .addField("value", 38.0)
//                .time(Instant.now(),WritePrecision.NS)
//                ;
//        writeApiBlocking.writePoint(point);

        // 2. 使用POJO类写入
        int count = 0;
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            DemoPOJO demoPOJO = new DemoPOJO("jack", (float) Math.random()*70, Instant.now());
            writeApiBlocking.writeMeasurement(WritePrecision.MS,demoPOJO);
            count++;
        }
//        DemoPOJO demoPOJO = new DemoPOJO("jack", 33, Instant.now());
//        writeApiBlocking.writeMeasurement(WritePrecision.MS,demoPOJO);

        // 3. 调用close方法会关闭并释放一些比如守护线程之类的对象。
        influxDBClient.close();
        System.out.println("write success, size = " + count);
    }
}
